<template>
    {{uid}}{{tid}}
    <el-button v-if="isaccept" @click="accept">接受</el-button>
    <video ref="v1" autoplay playsinline style="width: 300px;height: 300px"></video>
    <video ref="v2" autoplay playsinline style="width: 300px;height: 300px"></video>
</template>

<script  lang="ts" setup>
    import { onMounted,reactive,ref } from 'vue'
    import { useRoute,useRouter } from 'vue-router'
    import {websocketStore} from "../../store/websokcet.js";
    import socket from "../../utils/websocket.ts";

    const web = websocketStore();
    let route = useRoute();
    const v1 = ref();
    const v2 = ref();
    const pc = ref(null);
    const mystrea = ref();
    const uid = ref();
    const tid = ref();
    const isaccept = ref(false);

    const accept = ()=>{
        socket.send({uid:uid.value,to:tid.value,type:4})
    }

    const loginWebsocket = ()=>{
         Promise.resolve().then(()=>{
             socket.init()
         }).then(()=>{
             if (route.query.type == 1){
                  uid.value =  localStorage.getItem("im-userid")
                  // 获取连接上的from参数
                  tid.value = route.query.from
             }else {
                 uid.value =  localStorage.getItem("im-userid")
                 // 获取连接上的from参数
                 tid.value = route.query.from
                 isaccept.value = true
             }
             socket.send({uid:uid.value,type:1})
         }).then(()=>{
             if (route.query.type == 1){
                 socket.send({uid:uid.value,to:tid.value,type:3})
             }
         })
    }

    // 监听websocket发送的消息msg，收到返回的消息则触发
    web.$subscribe((mutations, state) => {
        let msg = JSON.parse(state.msg);
        switch (msg.type) {
            case 4:// 接收呼叫回应
                console.log("4")
                sxt().then(res=>{
                    socket.send({uid:uid.value,to:tid.value,type:5})
                })
                break;
            case 5:// 对方传递呼叫请求
              console.log("5")
                sxt().then(res=>{
                    if (pc.value == null){
                        createPeerConnection();
                    }
                    // 创建远端配置连接信息请求，参数一：方法调用成功回调函数，参数二：方法调用失败回调函数
                    pc.value.createOffer(createOfferAndSendMessage,handleCreateOfferError)
                })
                break;
            case 6:// 我方接收呼叫并回答对方请求
              console.log("6")
                if (pc.value == null) {
                    createPeerConnection()
                }
                console.log(msg.message)
                // 设置远端连接描述
                pc.value.setRemoteDescription(new RTCSessionDescription(msg.message));
                doAnswer()
                break;
            case 7:
                console.log("7")
                // 设置远端连接描述
                pc.value.setRemoteDescription(new RTCSessionDescription(msg.message));
                break;
            case 8:
                console.log("8:",msg)
                var candidate = new RTCIceCandidate({
                    sdpMLineIndex: msg.message.sdpMLineIndex,
                    candidate: msg.message.candidate
                });
                // 添加 iceCandidate 时调用
                pc.value.addIceCandidate(candidate)
                break;
        }
    });

    const handleCreateOfferError = ()=>{
        console.log("对方连接失败 ===>>>")
    }

    const createOfferAndSendMessage = (sessionDescription)=>{
        console.log("对方连接成功 ===>>>")
        // 连接成功后设置连接属性
        pc.value.setLocalDescription(sessionDescription)
        socket.send({uid:uid.value,to:tid.value,type:6,message:sessionDescription})
    }

    const doAnswer = ()=>{
        if (pc.value == null) {
            createPeerConnection()
        }
        pc.value.createAnswer().then(createAnswerAndSendMessage, handleCreateAnswerError);
    }

    const handleCreateAnswerError = ()=>{
        console.log("bbb")
    }

    const createAnswerAndSendMessage = (sessionDescription)=>{
        // 呼叫端设置本地 通知 描述
        pc.value.setLocalDescription(sessionDescription)
        // 发送给对方 通知
        socket.send({uid:uid.value,to:tid.value,type:7,message:sessionDescription})
    }

    const createPeerConnection = ()=>{
        // 创建连接
        pc.value = new RTCPeerConnection(null);
        pc.value.onicecandidate = handleIceCandidate;
        pc.value.onaddstream = handleRemoteStreamAdded;
        // 将音视频逐一添加到本地流
        for (const trac of mystrea.value.getTracks()){
            pc.value.addTrack(trac,mystrea.value);
        }
    }

    const handleRemoteStreamAdded = (event)=>{
        console.log('监听是否有媒体流接入:',event)
        v2.value.srcObject = event.stream;
    }

    const handleIceCandidate = (event)=>{
        console.log('RTCIceCandidate对象添加时触发event:',event)
        if (event.candidate){
            socket.send({uid:uid.value,to:tid.value,type:8,message:event.candidate})
        }
    }

    const closeRTC = () => {
        // 关闭视频通话
        pc.value.close()
    }

    //开启摄像头
    const sxt = ()=>{
        return new Promise((resolve,reject)=>{
            navigator.mediaDevices.getUserMedia({
                audio: true,
                video: true,
            }).then(stream => {
                // 获取到优化后的媒体流
                mystrea.value = stream
                v1.value.srcObject = stream  // 自己的流
            }).then(()=>resolve()).catch(err => {
                // 错误信息
                console.log("摄像头拉取失败：",err);
                reject();
            });
        })
    }

    onMounted(()=>{
        loginWebsocket();
    })
</script>

<style scoped>

</style>
